<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialog = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :span="24"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 === 0 ? 'bdtop':'','vcenter']"
            >
              <el-col :span="5">
                <el-row>
                  <el-tag closable @close="removeById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-row>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  :class="['bdtop', i2 === 0 ? 'bdtop':'','vcenter']"
                >
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeById(scope.row, item2.id)" >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeById(scope.row, item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑角色"
              placement="top"
              :enterable="false"
            >
              <el-button type="primary" icon="el-icon-edit" @click="getEditRoles(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除角色"
              placement="top"
              :enterable="false"
            >
              <el-button type="danger" icon="el-icon-delete" @click="removeRolesById(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button type="warning" icon="el-icon-setting" @click="fenpeiquanixan(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addRolesDialog" @close="clearAddRolesForm">
      <el-form ref="addRolesFormRef" :model="rolesForm" :rules="rolesFormRules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog title="编辑角色" :visible.sync="editRolesDialog" @close="clearEditRolesForm">
      <el-form
        ref="editRolesFormRef"
        :model="rolesForm"
        :rules="rolesFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="putEditRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="rightsDialogVisible" @close="clearRightIdList">
      <!-- 树形结构区域 -->
      <el-tree
        :data="rightsData"
        :props="treeProps"
        show-checkbox
        :highlight-current="true"
        default-expand-all
        node-key="id"
        :default-checked-keys="rightIdList"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="tijiaoquanxian">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleId: '',
      addRolesDialog: false,
      editRolesDialog: false,
      rightsDialogVisible: false,
      rolesList: [],
      rightsData: [],
      rightIdList: [],
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      rolesForm: {
        id: '',
        roleName: '',
        roleDesc: '',
      },
      // 表单校验规则
      rolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      //   console.log(this.rolesList)
    },
    // 删除权限
    async removeById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除！')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      // console.log(res);
      res.data.forEach(item => {
        if (item.children.length === 0) {
          // 删除
          const index = res.data.indexOf(item)
          res.data.splice(index, 1)
        }
        item.children.forEach(i => {
          if (i.children.length === 0) {
            const index = res.data.indexOf(item)
            res.data.splice(index, 1)
          }
        })

      })
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      role.children = res.data
    },

    // 添加角色
    async addRoles() {
      const { data: res } = await this.$http.post('roles', this.rolesForm)
      console.log(res)
      if (res.meta.status !== 201) return this.$message.error('添加角色失败')
      this.$message.success('添加角色成功')
      this.addRolesDialog = false
      this.getRolesList()
    },
    // 重置添加表单
    clearAddRolesForm() {
      this.$refs.addRolesFormRef.resetFields()
    },
    // 重置修改表单
    clearEditRolesForm() {
      this.$refs.editRolesFormRef.resetFields()
    },
    // 获取角色信息
    async getEditRoles(id) {
      const { data: res } = await this.$http.get(`/roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败！')
      }
      this.rolesForm.roleName = res.data.roleName
      this.rolesForm.roleDesc = res.data.roleDesc
      this.rolesForm.id = res.data.roleId
      this.editRolesDialog = true
    },
    // 提交编辑的角色信息
    async putEditRoles() {
      const { data: res } = await this.$http.put(
        `/roles/${this.rolesForm.id}`,
        {
          roleName: this.rolesForm.roleName,
          roleDesc: this.rolesForm.roleDesc,
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改角色信息失败！')
      }
      this.getRolesList()
      this.$message.success('修改角色成功')
      this.editRolesDialog = false
    },
    // 删除角色
    async removeRolesById(id) {
      const deleteConfirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (deleteConfirmResult !== 'confirm') {
        return this.$message.info('取消了删除！')
      }
      const { data: res } = await this.$http.delete(`/roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功')
      this.getRolesList()
    },
    // 为角色分配权限
    async fenpeiquanixan(role) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }
      this.$message.success('获取权限列表成功')
      //   console.log(res);
      this.rightsData = res.data
      this.roleId = role.id
      // console.log('id:', this.roleId);
      this.forEachRightslist(role, this.rightIdList)
      console.log(this.rightIdList);
      this.rightsDialogVisible = true
    },
    forEachRightslist(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.forEachRightslist(item, arr)
      })
    },
    // 关闭对话框时重置权限id数组
    clearRightIdList() {
      this.rightIdList = []
    },
    // 提交已经修改的权限
    async tijiaoquanxian() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('更新权限失败！')
      }
      this.$message.success('更新权限成功')
      this.rightsDialogVisible = false
      this.getRolesList()
    }
  },
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
